package com.atguigu.yuntai.govern.service.impl;

import com.atguigu.yuntai.govern.mapper.GovernConfigMapper;
import com.atguigu.yuntai.govern.service.DSTimeTaskGovernService;
import com.atguigu.yuntai.schedule.bean.DSTaskAvgTimeInstance;
import com.atguigu.yuntai.schedule.bean.DSTaskTimeInstance;
import com.atguigu.yuntai.schedule.mapper.DSTimeTaskGovernMapper;
import com.atguigu.yuntai.schedule.mapper.TDsTaskInstanceMapper;
import com.atguigu.yuntai.statistics.entity.*;
import com.atguigu.yuntai.statistics.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DSTimeTaskGovernServiceImpl implements DSTimeTaskGovernService {

    @Autowired
    private DSTimeTaskGovernMapper dsTimeTaskGovernMapper;

    @Autowired
    private GovernConfigMapper governConfigMapper;

    @Autowired
    private UserStatsMapper userStatsMapper;
    @Autowired
    private UserChangeMapper userChangeMapper;
    @Autowired
    private UserRetentionMapper userRetentionMapper;
    @Autowired
    private UserNewBuyerStatsMapper userNewBuyerStatsMapper;
    @Autowired
    private UserActionMapper userActionMapper;
    @Autowired
    private TradeStatsCateMapper tradeStatsCateMapper;
    @Autowired
    private TradeStatsTmMapper tradeStatsTmMapper;
    @Autowired
    private TradeStatsMapper tradeStatsMapper;
    @Autowired
    private TrafficStatsByChannelMapper trafficStatsByChannelMapper;
    @Autowired
    private RepeatPurchaseMapper repeatPurchaseMapper;
    @Autowired
    private OrderProvinceMapper orderProvinceMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private TDsTaskInstanceMapper taskInstanceMapper;
    /**
     * 校验DS调度器任务是否延迟  跟历史平均值对比
     */
    @Override
    public void TaskTimeDelayGovernance() {
        //查询最前三天数据（不包含当天数据） 并且是成功的任务
        List<DSTaskAvgTimeInstance> taskavgTimeList = dsTimeTaskGovernMapper.getSucessAvgTimeTaskLastThreeDays();
        //查询之后按taskcode聚合 求平均耗时
        Map<Long, Long> taskMap = new HashMap<>();
        taskavgTimeList.forEach(item -> taskMap.put(item.getTask_code(), item.getAvgTime()));
        //将历史数据放进hashmap后 查询当天任务
        List<DSTaskTimeInstance> taskTimeList = dsTimeTaskGovernMapper.getTodayTaskTime();
        //循环当天数据，并与历史数据进行判断 对比 超时或失败的发出预警通知
        int time_allowed = Integer.parseInt(governConfigMapper.getValueByKey("Time_Allowed"));
        taskTimeList.forEach(item -> {
            if (6 == item.getState() || 9 == item.getState()) {
                //任务失败
                PhoneWaring("您的订单号是：75231。已由顺风快递发出，请注意查收。", item.getPhone());
                //将已预警的表插入记录表 用于过滤定时器查询的数据
                dsTimeTaskGovernMapper.saveGovernAlertNotified(item.getName(), item.getTask_code(), item.getTask_type(), new Timestamp(System.currentTimeMillis()));
            } else if (7 == item.getState()) {
                //任务成功 判断任务时长 是否超时  超时发出预警通知
                //对比任务完成时间，如果超时 发出警告
                if (taskMap.containsKey(item.getTask_code())) {
                    //近三天有历史数据 根据近三天的任务平均时长 进行对比
                    Long avgTime = taskMap.getOrDefault(item.getTask_code(), 0l);
                    Long time = item.getTime_second();
                    int count = taskInstanceMapper.getTaskLastThreeDaysCount(item.getTask_code());
                    if (time - avgTime > time_allowed && count > 3) {
                        //如果当前任务运行时长大于平均时长 并且 历史三天任务数大于3个 且严重超时 超时大于配置项 则预警
                        PhoneWaring("您的订单号是：75231。已由顺风快递发出，请注意查收。", item.getPhone());
                        //将已预警的表插入记录表 用于过滤定时器查询的数据
                        dsTimeTaskGovernMapper.saveGovernAlertNotified(item.getName(), item.getTask_code(), item.getTask_type(), new Timestamp(System.currentTimeMillis()));
                    }
                }
            }
            //其他状态 不做任何逻辑
        });
    }


    // 达信通 互亿无线
    //电话预警
    public void PhoneWaring(String content, String mobile) {
//        HttpClient client = new HttpClient();
//        PostMethod method = new PostMethod(Constant.Url);
//        client.getParams().setContentCharset("utf-8");
//        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
//        NameValuePair[] data = {
//                new NameValuePair("account", Constant.APPID),
//                new NameValuePair("password", Constant.APIKEY),
//                new NameValuePair("mobile", mobile),
//                new NameValuePair("content", content)
//        };
//        method.setRequestBody(data);
//        try {
//            int result = client.executeMethod(method);
//            if (result != 200) {
//                throw new Exception("请求电话接口失败！ 状态码：" + result);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 定时监控各项指标 是否异常
     */
    @Override
    public void QuotaGovernance() {
        List<AdsUserStats> adsUserStatsYesterday = userStatsMapper.getAdsUserStatsYesterday();
        List<AdsUserStats> adsUserStateToday = userStatsMapper.getAdsUserStateToday();
        checkUserState(adsUserStatsYesterday, adsUserStateToday);

        List<AdsUserRetention> adsUserRetentionYesterday = userRetentionMapper.getAdsUserRetentionYesterday();
        List<AdsUserRetention> adsUserRetentionToday = userRetentionMapper.getAdsUserRetentionToday();
        checkUserRetention(adsUserRetentionYesterday, adsUserRetentionToday);

        AdsUserChange adsUserChangeYesterday = userChangeMapper.getAdsUserChangeYesterday();
        AdsUserChange adsUserChangeToday = userChangeMapper.getAdsUserChangeToday();
        checkUserChange(adsUserChangeYesterday, adsUserChangeToday);

        List<AdsUserAction> adsUserActionYesterday = userActionMapper.getAdsUserActionYesterday();
        List<AdsUserAction> adsUserActionToday = userActionMapper.getAdsUserActionToday();
        checkAdsUserAction(adsUserActionYesterday, adsUserActionToday);

        List<AdsTrafficStatsByChannel> adsTrafficStatsByChannelYesterday = trafficStatsByChannelMapper.getAdsTrafficStatsByChannelYesterday();
        List<AdsTrafficStatsByChannel> adsTrafficStatsByChannelToday = trafficStatsByChannelMapper.getAdsTrafficStatsByChannelToday();
        checkAdsTrafficStatsByChannel(adsTrafficStatsByChannelYesterday, adsTrafficStatsByChannelToday);

        List<AdsTradeStatsByTm> adsTradeStatsByTmYesterday = tradeStatsTmMapper.getAdsTradeStatsByTmYesterday();
        List<AdsTradeStatsByTm> adsTradeStatsByTmToday = tradeStatsTmMapper.getAdsTradeStatsByTmToday();
        checkAdsTradeStatsByTm(adsTradeStatsByTmYesterday, adsTradeStatsByTmToday);

        List<AdsTradeStatsByCate> adsTradeStatsByCateYesterday = tradeStatsCateMapper.getAdsTradeStatsByCateYesterday();
        List<AdsTradeStatsByCate> adsTradeStatsByCateToday = tradeStatsCateMapper.getAdsTradeStatsByCateToday();
        checkAdsTradeStatsByCate(adsTradeStatsByCateYesterday, adsTradeStatsByCateToday);

        List<AdsTradeStats> adsTradeStatsYesterday = tradeStatsMapper.getAdsTradeStatsYesterday();
        List<AdsTradeStats> adsTradeStatsToday = tradeStatsMapper.getAdsTradeStatsToday();
        checkAdsTradeStats(adsTradeStatsYesterday, adsTradeStatsToday);

        List<AdsRepeatPurchaseByTm> adsRepeatPurchaseByTmYesterday = repeatPurchaseMapper.getAdsRepeatPurchaseByTmYesterday();
        List<AdsRepeatPurchaseByTm> adsRepeatPurchaseByTmToday = repeatPurchaseMapper.getAdsRepeatPurchaseByTmToday();
        checkAdsRepeatPurchaseByTm(adsRepeatPurchaseByTmYesterday, adsRepeatPurchaseByTmToday);


        List<AdsOrderByProvince> adsOrderByProvincesYesterday = orderProvinceMapper.getAdsOrderByProvinceYesterday();
        List<AdsOrderByProvince> adsOrderByProvincesToday = orderProvinceMapper.getAdsOrderByProvinceToday();
        checkAdsOrderByProvince(adsOrderByProvincesYesterday, adsOrderByProvincesToday);

        List<AdsNewBuyerStats> adsNewBuyerStatsYesterday = userNewBuyerStatsMapper.getAdsNewBuyerStatsYesterday();
        List<AdsNewBuyerStats> adsNewBuyerStatsToday = userNewBuyerStatsMapper.getAdsNewBuyerStatsToday();
        checkAdsNewBuyerStats(adsNewBuyerStatsYesterday, adsNewBuyerStatsToday);
    }

    /**
     * 校验用户新增 活跃人数
     *
     * @param adsUserStatsYesterday
     * @param adsUserStateToday
     */
    private void checkUserState(List<AdsUserStats> adsUserStatsYesterday, List<AdsUserStats> adsUserStateToday) {
        //校验最近1日新增用户指标是否异常
        StringBuilder sb = new StringBuilder();
        adsUserStateToday.forEach(today_item -> adsUserStatsYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays()) {
                int newUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsUserStats_Recent_" + today_item.getRecentDays() + "Days_NewUserCount"));
                int activeUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsUserStats_Recent_" + today_item.getRecentDays() + "Days_ActiveUserCount"));
                String ct1 = Math.abs(today_item.getNewUserCount() - yesterday_item.getNewUserCount()) > newUserCount ?
                        "近" + today_item.getRecentDays() + "日新增用户数指标异常,超出阀值,超出值为" + Math.abs(today_item.getNewUserCount() - yesterday_item.getNewUserCount()) + " " : "";
                sb.append(ct1);
                String ct2 = Math.abs(today_item.getActiveUserCount() - yesterday_item.getActiveUserCount()) > activeUserCount ?
                        "近" + today_item.getRecentDays() + "日活跃用户数指标异常,超出阀值,超出值为" + Math.abs(today_item.getActiveUserCount() - yesterday_item.getActiveUserCount()) + " " : "";
                sb.append(ct2);
            }
        }));
        if (sb.length() > 0) {
            //说明有超出阀值的内容 进行电话预警
            String adsUserPhone = governConfigMapper.getValueByKey("AdsUserState_Phone");
            PhoneWaring(sb.toString(), adsUserPhone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsUserPhone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验用户留存率
     *
     * @param adsUserRetentionYesterday
     * @param adsUserRetentionToday
     */
    private void checkUserRetention(List<AdsUserRetention> adsUserRetentionYesterday, List<AdsUserRetention> adsUserRetentionToday) {
        StringBuilder sb = new StringBuilder();
        adsUserRetentionToday.forEach(today_item -> adsUserRetentionYesterday.forEach(yesterday_item -> {
            if (today_item.getRetentionDay() == yesterday_item.getRetentionDay()) {
                BigDecimal adsUserRetention_Rate = new BigDecimal(governConfigMapper.getValueByKey("AdsUserRetention_Rate")).setScale(2);
                System.out.println(today_item.getRetentionRate().subtract(yesterday_item.getRetentionRate()).abs().compareTo(adsUserRetention_Rate));
                String ctx = today_item.getRetentionRate().subtract(yesterday_item.getRetentionRate()).abs().compareTo(adsUserRetention_Rate) > 0 ?
                        "近" + today_item.getRetentionRate() + "日留存率异常,超出阀值,超出值为" +
                                today_item.getRetentionRate().subtract(yesterday_item.getRetentionRate()).abs() + " " : "";
                sb.append(ctx);
            }
        }));
        if (sb.length() > 0) {
            String adsUserRetentionPhone = governConfigMapper.getValueByKey("AdsUserRetention_Phone");
            PhoneWaring(sb.toString(), adsUserRetentionPhone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsUserRetentionPhone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验用户变动
     *
     * @param adsUserChangeYesterday
     * @param adsUserChangeToday
     */
    private void checkUserChange(AdsUserChange adsUserChangeYesterday, AdsUserChange adsUserChangeToday) {
        StringBuilder sb = new StringBuilder();
        int adsUserChange_Churn_Count = Integer.parseInt(governConfigMapper.getValueByKey("AdsUserChange_Churn_Count"));
        int adsUserChange_Back_Count = Integer.parseInt(governConfigMapper.getValueByKey("AdsUserChange_Back_Count"));
        String ctx1 = Math.abs(Long.parseLong(adsUserChangeToday.getUserBackCount()) - Long.parseLong(adsUserChangeYesterday.getUserBackCount()))
                > adsUserChange_Back_Count ? "回流用户数异常,异常值为" + Math.abs(Long.parseLong(adsUserChangeToday.getUserBackCount()) -
                Long.parseLong(adsUserChangeYesterday.getUserBackCount())) + " " : "";
        sb.append(ctx1);
        String ctx2 = Math.abs(Long.parseLong(adsUserChangeToday.getUserChurnCount()) - Long.parseLong(adsUserChangeYesterday.getUserChurnCount()))
                > adsUserChange_Churn_Count ? "流失用户数异常，异常值为" + Math.abs(Long.parseLong(adsUserChangeToday.getUserChurnCount()) -
                Long.parseLong(adsUserChangeYesterday.getUserChurnCount())) : "";
        sb.append(ctx2);
        if (sb.length() > 0) {
            String adsUserRetentionPhone = governConfigMapper.getValueByKey("AdsUserChange_Phone");
            PhoneWaring(sb.toString(), adsUserRetentionPhone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsUserRetentionPhone, new Timestamp(System.currentTimeMillis()));
        }

    }

    /**
     * 校验用户行为
     *
     * @param adsUserActionToday
     * @param adsUserActionYesterday
     */
    private void checkAdsUserAction(List<AdsUserAction> adsUserActionToday, List<AdsUserAction> adsUserActionYesterday) {
        StringBuilder sb = new StringBuilder();
        adsUserActionToday.forEach(today_item -> adsUserActionYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays()) {
                int orderCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsUserAction_Recent_" + today_item.getRecentDays() + "Days_Order_Count"));
                String ctx1 = Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) > orderCount ? "用户近" + today_item.getRecentDays() + "日下单人数异常," +
                        "异常值为" + Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) + " " : "";
                sb.append(ctx1);
                int paymentCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsUserAction_Recent_" + today_item.getRecentDays() + "Days_Payment_Count"));
                String ctx2 = Math.abs(today_item.getPaymentCount() - yesterday_item.getPaymentCount()) > paymentCount ? "用户近" + today_item.getRecentDays() + "日支付人数异常," +
                        "异常值为" + Math.abs(today_item.getPaymentCount() - yesterday_item.getPaymentCount()) + " " : "";
                sb.append(ctx2);
            }
        }));
        if (sb.length() > 0) {
            String adsUserRetentionPhone = governConfigMapper.getValueByKey("AdsUserAction_Phone");
            PhoneWaring(sb.toString(), adsUserRetentionPhone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsUserRetentionPhone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验流量统计 UV SV
     *
     * @param adsTrafficStatsByChannelYesterday
     * @param adsTrafficStatsByChannelToday
     */
    private void checkAdsTrafficStatsByChannel(List<AdsTrafficStatsByChannel> adsTrafficStatsByChannelYesterday, List<AdsTrafficStatsByChannel> adsTrafficStatsByChannelToday) {
        StringBuilder sb = new StringBuilder();
        adsTrafficStatsByChannelToday.forEach(today_item -> adsTrafficStatsByChannelYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays() && today_item.getChannel().equals(yesterday_item.getChannel())) {
                int uvCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTrafficStatsByChanner_Recent_" + today_item.getRecentDays() + "Days_Uv_Count"));
                int svCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTrafficStatsByChanner_Recent_" + today_item.getRecentDays() + "Days_Sv_Count"));
                String ctx1 = Math.abs(today_item.getUvCount() - yesterday_item.getUvCount()) > uvCount ? "用户在" + today_item.getChannel() + "渠道中，近" + today_item.getRecentDays() + "日uv访客人数异常," +
                        "异常值为" + Math.abs(today_item.getUvCount() - yesterday_item.getUvCount()) + " " : "";
                String ctx2 = Math.abs(today_item.getSvCount() - yesterday_item.getSvCount()) > svCount ? "用户在" + today_item.getChannel() + "渠道中,近" + today_item.getRecentDays() + "日sv会话数异常，" +
                        "异常值为" + Math.abs(today_item.getSvCount() - yesterday_item.getSvCount()) + " " : "";
                sb.append(ctx1).append(ctx2);
            }
        }));
        if (sb.length() > 0) {
            String adsTrafficStatsByChannelPhone = governConfigMapper.getValueByKey("AdsTrafficStatsByChanner_Phone");
            PhoneWaring(sb.toString(), adsTrafficStatsByChannelPhone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsTrafficStatsByChannelPhone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验各品类商品订单数 退单数 订单人数 退单人数
     * *
     *
     * @param adsTradeStatsByTmYesterday
     * @param adsTradeStatsByTmToday
     */
    private void checkAdsTradeStatsByTm(List<AdsTradeStatsByTm> adsTradeStatsByTmYesterday, List<AdsTradeStatsByTm> adsTradeStatsByTmToday) {
        StringBuilder sb = new StringBuilder();
        adsTradeStatsByTmToday.forEach(today_item -> adsTradeStatsByTmYesterday.forEach(yesterday -> {
            if (today_item.getRecentDays() == yesterday.getRecentDays() && today_item.getTmId().equals(yesterday.getTmId())) {
                int orderCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByTm_Recent_" + today_item.getRecentDays() + "Days_Order_Count"));
                int orderUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByTm_Recent_" + today_item.getRecentDays() + "Days_Order_User_Count"));
                int orderReundCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByTm_Recent_" + today_item.getRecentDays() + "Days_Order_Reund_Count"));
                int orderReundUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByTm_Recent_" + today_item.getRecentDays() + "Days_Order_Reund_User_Count"));
                String ctx1 = Math.abs(today_item.getOrderCount() - yesterday.getOrderCount()) > orderCount ? "商品在" + today_item.getTmName() + "品牌中订单数异常，异常值为"
                        + Math.abs(today_item.getOrderCount() - yesterday.getOrderCount()) + " " : "";
                String ctx2 = Math.abs(today_item.getOrderUserCount() - yesterday.getOrderUserCount()) > orderUserCount ? "商品在" + today_item.getTmName() + "品牌中订单人数异常，异常值为"
                        + Math.abs(today_item.getOrderUserCount() - yesterday.getOrderUserCount()) + " " : "";
                String ctx3 = Math.abs(today_item.getOrderRefundCount() - yesterday.getOrderRefundCount()) > orderReundCount ? "商品在" + today_item.getTmName() + "品牌中退单数异常，异常值为"
                        + Math.abs(today_item.getOrderRefundCount() - yesterday.getOrderRefundCount()) + " " : "";
                String ctx4 = Math.abs(today_item.getOrderRefundUserCount() - yesterday.getOrderRefundUserCount()) > orderReundUserCount ? "商品在" + today_item.getTmName() + "品牌中退单人数异常，异常值为"
                        + Math.abs(today_item.getOrderRefundUserCount() - yesterday.getOrderRefundUserCount()) + " " : "";
                sb.append(ctx1).append(ctx2).append(ctx3).append(ctx4);
            }
        }));
        if (sb.length() > 0) {
            String adsTradeStatsByTm_Recent_Phone = governConfigMapper.getValueByKey("AdsTradeStatsByTm_Phone");
            PhoneWaring(sb.toString(), adsTradeStatsByTm_Recent_Phone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsTradeStatsByTm_Recent_Phone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验各品类商品 订单数 退单数 订单人数 退单人数
     *
     * @param adsTradeStatsByCateYesterday
     * @param adsTradeStatsByCateToday
     */
    private void checkAdsTradeStatsByCate(List<AdsTradeStatsByCate> adsTradeStatsByCateYesterday, List<AdsTradeStatsByCate> adsTradeStatsByCateToday) {
        StringBuilder sb = new StringBuilder();
        adsTradeStatsByCateToday.forEach(today_item -> adsTradeStatsByCateYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays() && today_item.getCategory1Id().equals(yesterday_item.getCategory1Id())
                    && today_item.getCategory2Id().equals(yesterday_item.getCategory2Id()) && today_item.getCategory3Id().equals(yesterday_item.getCategory3Id())) {
                int orderCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByCate_Recent_" + today_item.getRecentDays() + "Days_Order_Count"));
                int orderUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByCate_Recent_" + today_item.getRecentDays() + "Days_Order_User_Count"));
                int orderRefundCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByCate_Recent_" + today_item.getRecentDays() + "Days_Order_Refund_Count"));
                int orderRefundUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStatsByCate_Recent_" + today_item.getRecentDays() + "Days_Order_Refund_User_Count"));
                String ctx1 = Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) > orderCount ? "商品在" + today_item.getCategory1Name() + today_item.getCategory2Name() +
                        today_item.getCategory3Name() + "分类中订单数异常,异常值为" + Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) + " " : "";
                String ctx2 = Math.abs(today_item.getOrderUserCount() - yesterday_item.getOrderUserCount()) > orderUserCount ? "商品在" + today_item.getCategory1Name() + today_item.getCategory2Name() +
                        today_item.getCategory3Name() + "分类中订单人数异常,异常值为" + Math.abs(today_item.getOrderUserCount() - yesterday_item.getOrderUserCount()) + " " : "";
                String ctx3 = Math.abs(today_item.getOrderRefundCount() - yesterday_item.getOrderRefundCount()) > orderRefundCount ? "商品在" + today_item.getCategory1Name() + today_item.getCategory2Name() +
                        today_item.getCategory3Name() + "分类中退单数异常,异常值为" + Math.abs(today_item.getOrderRefundCount() - yesterday_item.getOrderRefundCount()) + " " : "";
                String ctx4 = Math.abs(today_item.getOrderRefundUserCount() - yesterday_item.getOrderRefundUserCount()) > orderRefundUserCount ? "商品在" + today_item.getCategory1Name() + today_item.getCategory2Name() +
                        today_item.getCategory3Name() + "分类中退单人数异常,异常值为" + Math.abs(today_item.getOrderRefundUserCount() - yesterday_item.getOrderRefundUserCount()) + " " : "";
                sb.append(ctx1).append(ctx2).append(ctx3).append(ctx4);
            }
        }));
        if (sb.length() > 0) {
            String adsTradeStatsByCate_Recent_Phone = governConfigMapper.getValueByKey("AdsTradeStatsByCate_Phone");
            PhoneWaring(sb.toString(), adsTradeStatsByCate_Recent_Phone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsTradeStatsByCate_Recent_Phone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验交易综合统计
     *
     * @param adsTradeStatsYesterday
     * @param adsTradeStatsToday
     */
    private void checkAdsTradeStats(List<AdsTradeStats> adsTradeStatsYesterday, List<AdsTradeStats> adsTradeStatsToday) {
        StringBuilder sb = new StringBuilder();
        adsTradeStatsToday.forEach(today_item -> adsTradeStatsYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays()) {
                int orderCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStats_Recent_" + today_item.getRecentDays() + "Days_Order_Count"));
                int orderUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStats_Recent_" + today_item.getRecentDays() + "Days_Order_User_Count"));
                int orderRefundCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStats_Recent_" + today_item.getRecentDays() + "Days_Order_Refund_Count"));
                int orderRefundUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsTradeStats_Recent_" + today_item.getRecentDays() + "Days_Order_Refund_User_Count"));
                String ctx1 = Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) > orderCount ? "交易中订单数异常，异常值为" + Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) + " " : "";
                String ctx2 = Math.abs(today_item.getOrderUserCount() - yesterday_item.getOrderUserCount()) > orderUserCount ? "交易中订单人数异常，异常值为" + Math.abs(today_item.getOrderUserCount() - yesterday_item.getOrderUserCount()) + " " : "";
                String ctx3 = Math.abs(today_item.getOrderRefundCount() - yesterday_item.getOrderRefundCount()) > orderRefundCount ? "交易中退单数异常，异常值为" + Math.abs(today_item.getOrderRefundCount() - yesterday_item.getOrderRefundCount()) + " " : "";
                String ctx4 = Math.abs(today_item.getOrderRefundUserCount() - yesterday_item.getOrderRefundUserCount()) > orderRefundUserCount ? "交易中退单人数异常，异常值为" + Math.abs(today_item.getOrderRefundUserCount() - yesterday_item.getOrderRefundUserCount()) + " " : "";
                sb.append(ctx1).append(ctx2).append(ctx3).append(ctx4);
            }
        }));
        if (sb.length() > 0) {
            String adsTradeStats_phone = governConfigMapper.getValueByKey("AdsTradeStats_Phone");
            PhoneWaring(sb.toString(), adsTradeStats_phone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsTradeStats_phone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验各品牌复购率
     *
     * @param adsRepeatPurchaseByTmYesterday
     * @param adsRepeatPurchaseByTmToday
     */
    private void checkAdsRepeatPurchaseByTm(List<AdsRepeatPurchaseByTm> adsRepeatPurchaseByTmYesterday, List<AdsRepeatPurchaseByTm> adsRepeatPurchaseByTmToday) {
        StringBuilder sb = new StringBuilder();
        adsRepeatPurchaseByTmToday.forEach(today_item -> adsRepeatPurchaseByTmYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays() && today_item.getTmId().equals(yesterday_item.getTmId())) {
                BigDecimal repeatRate = new BigDecimal(governConfigMapper.getValueByKey("AdsRepeatPurchaseByTm_" + today_item.getRecentDays() + "Days_Order_Repeat_Rate"));
                String ctx1 = today_item.getOrderRepeatRate().subtract(yesterday_item.getOrderRepeatRate()).abs().
                        compareTo(repeatRate) == 1 ? today_item.getTmName() + "品牌近" + today_item.getRecentDays() + "日复购率异常,异常值为" +
                        today_item.getOrderRepeatRate().subtract(yesterday_item.getOrderRepeatRate()).abs() + " " : "";
                sb.append(ctx1);
            }
        }));
        if (sb.length() > 0) {
            String adsRepeatPurchaseByTm_phone = governConfigMapper.getValueByKey("AdsRepeatPurchaseByTm_Phone");
            PhoneWaring(sb.toString(), adsRepeatPurchaseByTm_phone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsRepeatPurchaseByTm_phone, new Timestamp(System.currentTimeMillis()));
        }
    }

    /**
     * 校验各省份订单数
     *
     * @param adsOrderByProvincesYesterday
     * @param adsOrderByProvincesToday
     */
    private void checkAdsOrderByProvince(List<AdsOrderByProvince> adsOrderByProvincesYesterday, List<AdsOrderByProvince> adsOrderByProvincesToday) {
        StringBuilder sb = new StringBuilder();
        adsOrderByProvincesToday.forEach(today_item -> adsOrderByProvincesYesterday.forEach(yesterday_item -> {
            if (today_item.getProvinceId().equals(yesterday_item.getProvinceId()) && today_item.getRecentDays() == yesterday_item.getRecentDays()) {
                int orderCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsOrderByProvince_Recent_" + today_item.getRecentDays() + "Days_Order_Count"));
                String ctx1 = Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) > orderCount ? today_item.getProvinceName() + "省份订单值异常，异常值为" +
                        Math.abs(today_item.getOrderCount() - yesterday_item.getOrderCount()) + " " : "";
                sb.append(ctx1);
            }
        }));
        if (sb.length() > 0) {
            String adsOrderByProvince_phone = governConfigMapper.getValueByKey("AdsOrderByProvince_Phone");
            PhoneWaring(sb.toString(), adsOrderByProvince_phone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsOrderByProvince_phone, new Timestamp(System.currentTimeMillis()));
        }
    }


    private void checkAdsNewBuyerStats(List<AdsNewBuyerStats> adsNewBuyerStatsYesterday, List<AdsNewBuyerStats> adsNewBuyerStatsToday) {
        StringBuilder sb = new StringBuilder();
        adsNewBuyerStatsToday.forEach(today_item -> adsNewBuyerStatsYesterday.forEach(yesterday_item -> {
            if (today_item.getRecentDays() == yesterday_item.getRecentDays()) {
                int orderUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsNewBuyerStats_Recent_" + today_item.getRecentDays() + "Days_New_Order_User_Count"));
                int paymentUserCount = Integer.parseInt(governConfigMapper.getValueByKey("AdsNewBuyerStats_Recent_" + today_item.getRecentDays() + "Days_New_Payment_User_Count"));
                String ctx1 = Math.abs(today_item.getNewOrderUserCount() - yesterday_item.getNewOrderUserCount()) > orderUserCount ? "近" + today_item.getRecentDays() + "日新增下单人数异常，异常值为" +
                        Math.abs(today_item.getNewOrderUserCount() - yesterday_item.getNewOrderUserCount()) + " " : "";
                String ctx2 = Math.abs(today_item.getNewPaymentUserCount() - yesterday_item.getNewPaymentUserCount()) > paymentUserCount ? "近" + today_item.getRecentDays() + "日新增支付人数异常，异常值为" +
                        Math.abs(today_item.getNewPaymentUserCount() - yesterday_item.getNewPaymentUserCount()) + " " : "";
                sb.append(ctx1).append(ctx2);
            }
        }));
        if (sb.length() > 0) {
            String adsNewBuyerStats_phone = governConfigMapper.getValueByKey("AdsNewBuyerStats_Phone");
            PhoneWaring(sb.toString(), adsNewBuyerStats_phone);
            governConfigMapper.saveGovernPhoneRecord(sb.toString(), adsNewBuyerStats_phone, new Timestamp(System.currentTimeMillis()));
        }

    }
}
